// 内存数据库模拟器
class MemoryDB {
    constructor() {
        this.collections = new Map();
        this.connected = false;
    }

    async connect() {
        console.log('📦 连接到内存数据库...');
        this.connected = true;
        
        // 初始化默认数据
        this.collections.set('users', new Map([
            ['admin', {
                _id: 'admin',
                username: 'admin',
                password: '$2b$10$8K1p/a0d.LV9M.5Y4O5Y1.1YJ4Y5O5Y1Y5O5Y1Y5O5Y1Y5O5Y1Y5O', // admin123
                email: 'admin@devops.com',
                role: 'admin',
                permissions: ['read', 'write', 'admin'],
                createdAt: new Date(),
                lastLogin: new Date()
            }]
        ]));
        
        this.collections.set('alerts', new Map());
        this.collections.set('tickets', new Map());
        this.collections.set('knowledge', new Map());
        
        console.log('✅ 内存数据库连接成功');
        return true;
    }

    collection(name) {
        if (!this.collections.has(name)) {
            this.collections.set(name, new Map());
        }
        
        return {
            find: (query = {}) => ({
                toArray: () => Array.from(this.collections.get(name).values())
                    .filter(doc => this.matchQuery(doc, query))
            }),
            findOne: (query) => {
                const docs = Array.from(this.collections.get(name).values());
                return docs.find(doc => this.matchQuery(doc, query));
            },
            insertOne: (doc) => {
                const id = doc._id || Math.random().toString(36);
                doc._id = id;
                this.collections.get(name).set(id, doc);
                return { insertedId: id };
            },
            updateOne: (query, update) => {
                const docs = Array.from(this.collections.get(name).entries());
                const [id, doc] = docs.find(([_, doc]) => this.matchQuery(doc, query)) || [];
                if (doc) {
                    Object.assign(doc, update.$set || update);
                    this.collections.get(name).set(id, doc);
                    return { modifiedCount: 1 };
                }
                return { modifiedCount: 0 };
            },
            deleteOne: (query) => {
                const docs = Array.from(this.collections.get(name).entries());
                const [id] = docs.find(([_, doc]) => this.matchQuery(doc, query)) || [];
                if (id) {
                    this.collections.get(name).delete(id);
                    return { deletedCount: 1 };
                }
                return { deletedCount: 0 };
            }
        };
    }

    matchQuery(doc, query) {
        return Object.entries(query).every(([key, value]) => doc[key] === value);
    }

    async close() {
        console.log('📦 关闭内存数据库连接');
        this.connected = false;
    }
}

// Redis内存模拟
class MemoryRedis {
    constructor() {
        this.store = new Map();
        this.connected = false;
    }

    async connect() {
        console.log('📦 连接到内存Redis...');
        this.connected = true;
        console.log('✅ 内存Redis连接成功');
    }

    async get(key) {
        return this.store.get(key) || null;
    }

    async set(key, value, options = {}) {
        this.store.set(key, value);
        if (options.EX) {
            setTimeout(() => this.store.delete(key), options.EX * 1000);
        }
        return 'OK';
    }

    async del(key) {
        return this.store.delete(key) ? 1 : 0;
    }

    async exists(key) {
        return this.store.has(key) ? 1 : 0;
    }

    async quit() {
        console.log('📦 关闭内存Redis连接');
        this.connected = false;
    }
}

module.exports = { MemoryDB, MemoryRedis };